package org.goat.caprabank.server;

import java.util.List;

import org.goat.caprabank.shared.entity.BankTransaction;
import org.goat.caprabank.shared.entity.User;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class DataStore {
	private final Objectify objectify;

	public DataStore() {
		ObjectifyService.register(BankTransaction.class);
		ObjectifyService.register(User.class);
		objectify = ObjectifyService.begin();
	}

	public User findUserByUsername(String username) {
		List<User> queryResult = objectify.query(User.class).filter("username", username).list();
		return (queryResult == null || queryResult.isEmpty()) ? null : queryResult.get(0);
	}

	public User findUserByAccountNum(long accountNum) {
		return objectify.find(User.class, accountNum);
	}

	public int countUsers() {
		return objectify.query(User.class).count();
	}

	public List<BankTransaction> findTransactionsToAccount(User user) {
		return objectify.query(BankTransaction.class).filter("toAccount", user.accountNum).list();
	}

	public List<BankTransaction> findTransactionsFromAccount(User user) {
		return objectify.query(BankTransaction.class).filter("fromAccount", user.accountNum).list();
	}

	public void saveUser(User user) {
		objectify.put(user);
	}

	public void saveTransaction(BankTransaction transaction) {
		objectify.put(transaction);
	}
}
